<template>
  <div class="page-register">
    <article class="header">
      <header>
        <a href="#" class="site-logo">
          <img src="../assets/img/logo.png" alt />
        </a>
        <span class="login">
          <em class="blod">已有大风车账号？</em>
          <a href="/login">
            <el-button type="primary" size="smll">登录</el-button>
          </a>
        </span>
      </header>
    </article>
    <section>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="昵称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
          <el-button size="mini" round @click="sendMsg">发送验证码</el-button>
          <span class="status">{{statusMsg}}</span>
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <el-input v-model="ruleForm.code" maxlength="4"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="register('ruleForm')">同意协议并且注册</el-button>
          <div class="error">{{error}}</div>
          <a class="f1" href="http://www.meituan.com/about/terms" target="_blank">《大风车用户协议》</a>
        </el-form-item>
      </el-form>
    </section>s
  </div>
</template>

<script>
import CryptoJS from "crypto-js";
export default {
  layout: "blank",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        name: "",
        pass: "",
        checkPass: "",
        email: "",
        code: ""
      },
      statusMsg: "",
      error: "",
      rules: {
        name: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        pass: [{ required: true, validator: validatePass, trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        checkPass: [
          { required: true, validator: validatePass2, trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ]
      }
    };
  },
  methods: {
    //注册
    register() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          this.$axios
            .post("/users/signup", {
              username: window.encodeURIComponent(this.ruleForm.name),
              password: CryptoJS.MD5(this.ruleForm.pass).toString(),
              email: this.ruleForm.email,
              code: this.ruleForm.code
            })
            .then(({ status, data }) => {
              if (status === 200) {
                if (data && data.code === 0) {
                  location.href = "/login";
                  // alert("okkkk")
                } else {
                  alert("出错了");
                  console.log(status, data);
                }
              } else {
                this.error = `服务器崩了，错误码：${status}`;
              }
              setTimeout(() => {
                this.error = "";
              }, 1500);
            });
        }
      });
    },
    //验证码
    sendMsg() {
      let namePass;
      let emailPass;
      if (this.timerid) {
        return false;
      }
      this.$refs["ruleForm"].validateField("name", valid => {
        namePass = valid;
      });
      this.statusMsg = "";
      if (namePass) {
        return false;
      }
      this.$refs["ruleForm"].validateField("email", valid => {
        emailPass = valid;
      });
      if (!namePass && !emailPass) {
        this.$axios
          .post("/users/verify", {
            username: encodeURIComponent(this.ruleForm.name),
            email: this.ruleForm.email
          })
          .then(({ status, data }) => {
            if (status === 200 && data && data.code === 0) {
              let count = 60;
              this.statusMsg = `验证码已发送，剩余 ${count--}秒`;
              this.timerid = setInterval(() => {
                this.statusMsg = `验证码已发送，剩余 ${count--}秒`;
                if (count == -1) {
                  clearInterval(this.timerid);
                  // this.statusMsg = '';
                }
              }, 1000);
            } else {
              this.statusMsg = data.msg;
            }
          });
      }
    }

    /*      */
  }
};
</script>

<style lang="scss" >
@import "@/assets/css/register/index.scss";
.f1 {
  color: red;
  text-decoration: none;
}
</style>
